package com.aatrox.bhsypro.controller;

import com.aatrox.bhsypro.entity.BUser;
import com.aatrox.bhsypro.entity.BhSyByUser;
import com.aatrox.bhsypro.entity.BhSyGos;
import com.aatrox.bhsypro.entity.BhSyShop;
import com.aatrox.bhsypro.service.BhSyByUserService;
import com.aatrox.bhsypro.service.BhSyGosService;
import com.aatrox.bhsypro.service.BhSyShopService;
import com.aatrox.bhsypro.util.CookieUtil;
import com.aatrox.bhsypro.util.JsonResult;
import com.aatrox.bhsypro.util.QiniuUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
public class BhSyShopAjaxController {

    String path = "";
    String url = "";
    @RequestMapping(value = "/goods/uploadImg",method = RequestMethod.POST)
    public JsonResult uploadGosImg(@RequestParam("file") MultipartFile file){
        String key = "";
        if (!path.equals("")&&!url.equals("")){
            System.out.println("图片路径为:"+path);
            File fafter = new File(path);
            fafter.delete();
            //删除七牛云上的图片
            key = "http://r1xjdohxw.hn-bkt.clouddn.com/"+url;
        }
        if (file!=null){
            String fpath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            File upload = new File(fpath,"static/images/upload/");
            if(!upload.exists()) upload.mkdirs();
            path = upload.getAbsolutePath()+"\\"+file.getOriginalFilename();
            String huizhui = path.substring(path.indexOf("."));
            if (!".jpg".equals(huizhui) && !".png".equals(huizhui)){
                return new JsonResult(500,"只能上传jpg，png图片文件",null);
            }
            File f = new File(path);
            //移动图片
            try {
                file.transferTo(f);
                url = QiniuUpload.upload(f);
                System.out.println("商品图片七牛云命名为:"+url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HashMap hm = new HashMap();
        hm.put("shopImgPath","http://r1xjdohxw.hn-bkt.clouddn.com/"+url);
        return new JsonResult(200,"上传图片成功",hm);
    }
    @Autowired
    BhSyShopService bsss;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    BhSyByUserService bsbus;

    @RequestMapping(value = "/qiangG",method = RequestMethod.POST)
    public JsonResult qiangG(int sid, float bMoney , HttpServletRequest request, HttpSession session){
        String ticket = CookieUtil.getCookieValue(request,"userTicket");

        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        //获取Redis中用户商品是否购买
        Integer shopStatic = (Integer) redisTemplate.opsForValue().get("Shop:"+sid+":"+user.getUPassword());
        //获取用户商品库存
        Integer shopCount = (Integer) redisTemplate.opsForValue().get("Shop:"+sid);
        if (shopStatic!=null){
            return new JsonResult(509,"已经抢购此商品",null);
        }else {
            if (shopCount!=0){
                BhSyByUser bsbu = new BhSyByUser(sid,user.getUid(),1,bMoney);
                bsbus.insertUserShop(bsbu);
                bsss.updateShopCount(sid);
                redisTemplate.opsForValue().set("Shop:"+sid+":"+user.getUPassword(),1);
                shopCount=shopCount-1;
                redisTemplate.opsForValue().set("Shop:"+sid,shopCount);
            }else {
                return new JsonResult(510,"商品库存不足",null);
            }
        }
        return new JsonResult(200,"抢购成功",null);
    }

    @RequestMapping(value = "/countForS",method = RequestMethod.POST)
    public JsonResult countForS(HttpServletRequest request,HttpSession session){
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        String uri = request.getRequestURI();
        Integer count = (Integer) redisTemplate.opsForValue().get(uri+":"+user.getUid());
        System.out.println("{访问地址:}"+uri);
        if (count==null){
            redisTemplate.opsForValue().set(uri+":"+user.getUid(),1,5, TimeUnit.SECONDS);
        }else if (count<=5){
            redisTemplate.opsForValue().increment(uri+":"+user.getUid());
        }else if (count>5){
            return new JsonResult(511,"频繁访问",null);
        }
        HashMap hm = new HashMap();
        hm.put("staticI",redisTemplate.opsForValue().get(uri+":"+user.getUid()));
        return new JsonResult(200,"抢购中..",hm);
    }


    @RequestMapping("/cShopRed/{sid}")
    public JsonResult cShopRed(@PathVariable("sid") int sid, HttpServletRequest request){
        BhSyShop bss = bsss.selShopForSid(sid);
        System.out.println("{商品为:}"+bss);
        redisTemplate.opsForValue().set("Shop:"+sid,bss.getSCount());
        System.out.println("{商品ID:}"+ redisTemplate.opsForValue().get("Shop:"+sid));
        return new JsonResult(200,"成功",null);
    }

    @Autowired
    BhSyGosService bsgs;


    @PostMapping(value = "/uploadShop")
    public JsonResult uploadShop(BhSyShop shop,HttpServletRequest request,HttpSession session){
        System.out.println("{添加商品的信息}"+shop);
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        BhSyGos bss = bsgs.selGosForUid(user.getUid());
        shop.setGid(bss.getGid());
        System.out.println("{添加商品的信息}"+shop);
        bsss.insertNewShop(shop);

        return new JsonResult(200,"商品上传成功",null);
    }
}
